package com.zx._10_设计模式.创建型模式.原型模式;

import com.zx._10_设计模式.创建型模式.原型模式.model.Model2;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Prototype2 {

    private static byte[] data;

    static {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutput out = new ObjectOutputStream(baos);) {
            out.writeObject(new Model2());
            data = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Model2 getObj() {
        try (ByteArrayInputStream input = new ByteArrayInputStream(data);
                ObjectInput in = new ObjectInputStream(input);) {
            return (Model2) in.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(Prototype2.getObj());
        System.out.println(Prototype2.getObj());
        System.out.println(Prototype2.getObj());
    }
}
